define(function(require, exports, module) {
	var $ = require('jquery')
	require('jquery.tmpl')
	var Spine = require('spine')
	var FileItem = Spine.Controller.sub({
		elements: {
			'.filename-edit': 'fileNameEdit'
		},
		events: {
			'click': 'toggle',
			'dblclick': 'open',
			'click .filename-edit': 'stopPropagation',
			'change .filename-edit': 'update',
			'click .filename-view a': function(event) {
				event.preventDefault()
			},
			'focusout .filename-edit': 'finishEdit'
		},
		init: function() {
			if (!this.model) throw '@item required'
			DirectoryItem.bind('move', this.proxy(this.move))
			this.model.bind('update', this.proxy(this.render))
			this.model.bind('destroy', this.proxy(this.release))
			this.model.controller = this
		},
		render: function() {
			this.replace($("#fileTemplate").tmpl(this.model))
			return this
		},
		toggle: function(event) {
			this.el.toggleClass('selected')
			if (this.el.hasClass('selected')) {
				this.el.siblings().removeClass('editing')
			}
			FileItem.trigger('operate')
		},
		open: function() {
			if (this.model.type == 'folder') {
				App.trigger('open', {
					'name': this.model.filename,
					'type': this.model.type,
					'path': this.model.path
				})
			}
		},
		download: function() {
			if (this.el.hasClass('selected')) {
				$.post('/downloads', {
					'filename': this.model.filename,
					'path': this.model.path,
					'type': this.model.type
				}, function(data) {
					window.location.href = data.export_url
					console.log(data)
				}, 'json');
			}
		},
		delete: function() {
			this.model.destroy(true)
		},
		move: function(trac) {
			if (this.el.hasClass('selected')) {
				if (trac.path == App.getCurrentLocation || trac.path + '/' == App.getCurrentLocation) return
				if (trac.path == '/') trac.path = ''
				$.post('move', {
					source: this.model.path,
					target: trac.path + '/' + this.model.filename
				}, function(data) {
					console.log(data)
				})
				this.model.destroy()
			}
		},
		update: function(event) {
			var target = this.fileNameEdit.val()
			if (!target) {
				alert('Illegal input')
				this.fileNameEdit.val(this.model.filename)
				return
			}
			this.model.updateAttributes({
				'filename': target,
				'path': App.getCurrentLocation() + target
			}, true)
		},
		finishEdit: function() {
			if (event.which == 13) {

				if (!this.fileNameEdit.val()) {
					return
				}
				this.fileNameEdit.blur()
				this.el.removeClass('editing')
				if (this.el.hasClass('new') && this.model.filename == 'New Folder') {
					this.model.destroy(true)
				}
			}

		},
		stopPropagation: function(event) {
			event.stopPropagation()
		}
	})
	FileItem.extend(Spine.Events)

	module.exports = FileItem
	var App = require('./app')
	var DirectoryItem = require('./directoryitem')
})